<script lang="ts" setup>
  import { ref, reactive, watch, onMounted, computed, onActivated, onDeactivated, nextTick } from 'vue';
  import LiveChat from '@/components/LiveChat.vue';
  import SwitchToggle from '@/components/SwitchToggle.vue'
  import GlobalDialog from '@/components/GlobalDialog.vue';
  import { dialog } from '@/utils/dialog'
  import Orchestrator from "@/logic/audioOrchestrator";
  import { useRouter } from 'vue-router';
  import { useStore } from '@/stores/data'

  const store = useStore()
  const router = useRouter()
  const ok = ref(false)
  // 确认弹窗状态
  const showConfirmDialog = ref(false)
  const showConfirmDialogA = ref(false)
  const timeText = ref('')
  // const { connect: connectAudio, attachAudio,  queueSize, isPlaying } = useAudioWS();
  const audioRef = ref<HTMLAudioElement | null>(null);
  // 背景音乐播放器（不展示控件）
  let bgm: HTMLAudioElement | null = null;
  // 开启直播
  function enableAll() {
    console.log(store.userConfig.enableAll)
    // if(!store.userConfig.enableAll) {
      // chat.sendSetUserConfig({
      //   enableAll: true
      // });
    // }

    // 建立音频通道，用于语音播放（隐藏的 off-DOM audio） 
    // connectAudio();
    // if (!audioRef.value) {
    //   const el = new Audio();
    //   el.autoplay = true;
    //   // @ts-ignore
    //   el.playsInline = true; // 兼容 iOS 内联播放
    //   el.muted = false;
    //   audioRef.value = el;
    // }
    // attachAudio(audioRef.value);

    // 启动背景音乐（从 public/bgm.mp3 读取，可根据需要更换路径）
    if (!bgm) {
      bgm = new Audio('/bgm.mp3');
      bgm.loop = true;
      bgm.volume = 0.3;
      // @ts-ignore
      bgm.playsInline = true;
      bgm.autoplay = true;
      
      // 检查音频源是否有效
      bgm.addEventListener('error', (e) => {
        console.warn('背景音乐文件不存在或加载失败，跳过背景音乐播放');
        bgm = null; // 清除无效的音频引用
      });
      
      // 检查音频是否可播放
      bgm.addEventListener('canplay', () => {
        bgm?.play().catch((error) => {
          console.warn('背景音乐自动播放失败:', error);
          const oncePlay = () => {
            bgm?.play().finally(() => {
              window.removeEventListener('click', oncePlay);
              window.removeEventListener('touchstart', oncePlay);
            });
          };
          window.addEventListener('click', oncePlay, { once: true });
          window.addEventListener('touchstart', oncePlay, { once: true });
        });
      });
      
      // 如果音频源无效，立即触发错误处理
      bgm.addEventListener('loadstart', () => {
        setTimeout(() => {
          if (bgm && bgm.readyState === 0) {
            console.warn('音频源加载超时，可能文件不存在');
            bgm.dispatchEvent(new Event('error'));
          }
        }, 1000);
      });
    }
  }
  // 关闭直播
  const liveClose = () => {
    showConfirmDialog.value = true
  }
   // 关闭直播
  const liveCloseA = () => {
    showConfirmDialogA.value = true
  }
  
  // 确认结束直播
  const confirmLiveClose = async () => {
    // 断开websocket
    // chat.disconnect()
    store.updateConfig({enableAll: false})
    await store.stopInstance(store.runningData.key ,store.runningData.uhostId)
    Orchestrator.onLogout()
    if (store.enableTimeData.timeIntervalTimer) {
      clearInterval(store.enableTimeData.timeIntervalTimer)
      store.enableTimeData.timeIntervalTimer = null
      console.log('结束直播清除定时器')
    }
    console.log('直播已结束')
    router.push('/')
    // 这里可以添加实际的结束直播逻辑
  }


   const confirmLiveCloseA = async () => {
    // 断开websocket
    // chat.disconnect()
    store.updateConfig({enableAll: false})
    Orchestrator.onLogout()
    if (store.enableTimeData.timeIntervalTimer) {
      clearInterval(store.enableTimeData.timeIntervalTimer)
      store.enableTimeData.timeIntervalTimer = null
      console.log('结束直播清除定时器')
    }
    console.log('直播已结束')
    store.isLive = false
    window.location.assign('/')
    // 这里可以添加实际的结束直播逻辑
  }
  const chatRef = ref();
  // 监听弹幕数据的变化
  watch(store.liveData.danmu, (newval) => {
    sendChatMessage(newval[newval.length -1].content, newval[newval.length -1])
    liveDataChange()
  })
  // 发送聊天消息的方法
  const sendChatMessage = (message: string, options: Partial<ChatMessage> = {}) => {
    let msg = null
    let gift = null
    if (chatRef.value) {
      switch (options.type) {
        case "chat":
          msg = message
          break;
        case "follow":
          msg = '关注了主播'
          break;
        case "gift":
          msg = null
          gift = { name: options.gift_name, count: options.count }
          break;
        default:
          break;
      }
      if(options.type === 'chat' || options.type === 'follow' || options.type === 'gift') {
        chatRef.value.addChatMessage(msg, {
          username: options.user_name,
          isVip: false,
          isFan: true,
          isAdmin: false,
          gift
        });
      }
    }
  };
  // 页面导航方法
  const toList = () => {
    // 弹幕问题记录
    router.push('/danmuList');
  };
  const configSet = () => {
    // 主配置修改
    store.configTabId = 1
    router.push('/config?isLive=true');
  };
  const toInterval = () => {
    // 话术间隔时长
    router.push('/interval');
  };
  const toLiveConfig = (query: { name: string, title: string }) => {
    router.push({
      name: 'LiveConfig',
      query
    })
  };
  const toDeepseekConfig = (query: { name: string, title: string }) => {
    router.push({
      name: 'DeepseekConfig',
      query
    })
  };


  // 更新直播数据
  const liveDataChange = () => {
    const data = {
      type: 'update',
      title: 'NEXTAI',
      zaixian: store.liveData.current,
      changguan: store.liveData.total,
    }
    // console.log('给 uni-app 发送数据', data)
    // 检查uni对象是否存在（在WebView环境中）
    if (typeof uni !== 'undefined') {
      uni.postMessage({
        data: data,
      })
    } else {
      console.warn('uni对象不存在，可能不在WebView环境中')
    }
  }
  
  // 通用的配置更新函数
  const updateConfig = (configKey: string, value: any) => {
    Orchestrator.sendSetUserConfig({ [configKey]: value })
  }

  // 各个开关的变更处理函数
  const enableMainChange = (value: any) => {
    updateConfig('enableMain', value.detail.value)
  }
  const enableLikeChange = (value: any) => {
    updateConfig('enableLike', value.detail.value)
  }
  const enableFollowChange = (value: any) => {
    updateConfig('enableFollow', value.detail.value)
  }
  const enableGiftChange = (value: any) => {
    updateConfig('enableGift', value.detail.value)
  }
  const enableWelcomeChange = (value: any) => {
    updateConfig('enableWelcome', value.detail.value)
  }
  // DeepSeek 开关是否禁用（未配置时禁用）
  const isDeepSeekDisabled = computed(() => {
    return !store.userConfig.dsApiKey || !store.userConfig.dsModel
  })

  const enableSmartReplyChange = (value: any) => {
    if(isDeepSeekDisabled.value) {
      dialog.alert({message: "请先配置deepseek"});
      return;
    }
    updateConfig('enableSmartReply', value.detail.value)
  }

  // DeepSeek 开关点击处理（即使禁用也会触发）
  const handleDeepSeekClick = () => {
    if(isDeepSeekDisabled.value) {
      dialog.alert({message: "请先配置deepseek"});
    }
  }

  // 实时获取当前时间
  const nowTime = computed(() => {
    const now = new Date()
    const hours = now.getHours().toString().padStart(2, '0')
    const minutes = now.getMinutes().toString().padStart(2, '0')
    return `${hours}时${minutes}分`
  })
  
  // 报时方法
  const timeAnnouncement = () => {
    console.log('执行报时方法')
    const timeText = `${store.enableTimeData.timePrefix || ''}${nowTime.value}${store.enableTimeData.timeSuffix || ''}`
    Orchestrator.addEvent(timeText, 'interrupt')
  }
  
  // 定时器管理函数
  const manageTimeIntervalTimer = () => {
    // 清除之前的定时器
    if (store.enableTimeData.timeIntervalTimer) {
      clearInterval(store.enableTimeData.timeIntervalTimer)
      store.enableTimeData.timeIntervalTimer = null
    }
    // 如果报时设置开启，则启动定时器
    if (store.enableTimeData.enableTime) {
      
      const interval = store.enableTimeData.timeInterval
      if (interval) {
        // 设置定时器
        store.enableTimeData.timeIntervalTimer = setInterval(() => {
          timeAnnouncement()
        }, interval * 60 * 1000) as any // 转换为毫秒，使用 any 避免类型错误
      }
    }
  }
  
  // 报时设置开关变更处理
  const enableTimeChange = (value: any) => {
    store.enableTimeData.enableTime = value.detail.value
    // 立即执行一次报时
    if(value.detail.value) {
      timeAnnouncement()
    }
    // 管理定时器
    manageTimeIntervalTimer()
  }
  
  // 监听时间间隔变化
  watch(() => store.enableTimeData.timeInterval, (newInterval, oldInterval) => {
    if (newInterval !== oldInterval && store.enableTimeData.enableTime) {
      manageTimeIntervalTimer()
    }
  })

  // async function addMain()   { Orchestrator.addMain("这是主话术示例"); }
  


  //  watch(store.userConfig.enableMain, (newval) => {
  //   console.log('enableMain 变更', newval)
  //   if(newval) {  
  //     addMain()
  //   }
  // })

  // 组件挂载时设置全局方法，以便WebView可以调用
  onMounted(async () => {
    // 只在首次加载页面时调用 enableAll
    // 2) 用本次“用户手势”的点击顺便解锁自动播放（很关键）
    
    // setInterval(async () => {

    //   await addMain()

    // }, 10000)
    // await Orchestrator.sendGetUserConfig()
    console.log('1211111111111', store.userConfig)
    await store.getProfile()
    await store.getConfig()
    await store.runningInstance(store.userInfo.licenseKey)
    if(store.platform == 1) {
        await Orchestrator.onLogin();

    }else {
        await Orchestrator.onLoginWx()
    }
    
   
    // if (!store.pageStates.liveViewInitialized) {
    //   manageTimeIntervalTimer()
    //   enableAll()
    //   store.pageStates.liveViewInitialized = true
    // }
    
    // 监听UniAppJSBridge事件
    document.addEventListener('UniAppJSBridgeReady', () => {
      console.log('UniAppJSBridge已准备就绪')
    })
  })

  // 使用 keep-alive 相关生命周期来避免返回时重新加载
  // onActivated(async () => {
  //   // 页面激活时，保持现有状态，不重新初始化
  //   console.log('LiveView页面激活，保持现有状态')
    
  //   // 返回页面时，确保 LiveChat 组件滚动到底部
  //   if (chatRef.value) {
  //     nextTick(() => {
  //       chatRef.value.scrollToBottom()
  //     })
  //   }
  // })

  // onDeactivated(() => {
  //   // 页面失活时，保持状态以便返回时恢复
  //   console.log('LiveView页面失活，保持状态')
  // })

  const toAlgin = async () => {
    const res = await Orchestrator.unlockAudio()
    console.log(res)
    ok.value = res
    await Orchestrator.onLogin();
    await Orchestrator.sendDanmu(store.userConfig.dyName)
  }

</script>

<template>
  <div class="live-page">
    <div class="logo-block">
			<img class="logo" src="@/assets/images/login/logo.png" mode=""></img>

		</div>
    
    <div class="live">
			<div class="live-data-list-btn" @click="toList">弹幕记录</div>
			<div class="live-data">
				<div class="posTop">直播数据</div>
				<div class="item-block" v-if="true">
					<!-- <div class="items">
						<div class="text">点赞</div>
						<div class="number">0</div>
					</div>
					<div class="line"></div> -->
					<div class="items">
						<div class="text">场观</div>
						<div class="number">{{store.liveData.total || 0}}</div>
					</div>
					<div class="line"></div>
					<div class="items">
						<div class="text">当前人数</div>
						<div class="number">{{store.liveData.current || 0}}</div>
					</div>
				</div>
        <div class="item-block" v-else>
					<div class="but" style="margin-top: 200px;">
            <button @click="toAlgin">继续直播</button>
          </div>
				</div>
			</div>
			<div class="live-mssage">
				<!-- <live-msg ref="liveMsg"></live-msg> -->
        <!-- <LiveDanmaku ref="danmakuRef" :width="365" :height="141" /> -->
        <LiveChat ref="chatRef" :width="365" :height="141" />
			</div>
		</div>
    <div class="deepseek baseStyle" @click="configSet">
			<div class="title">
				<div class="text">主配置修改</div>
				<div class="icon"></div>
			</div>
		</div>
    <div class="control baseStyle">
			<div class="title">
				<div class="text">场控设置</div>
				<!-- <switch :checked="control == 1" @change="controlChange"/> -->
			</div>
			<div class="content">
				<div class="items" @click="toLiveConfig({ name: 'interval', title: '话术间隔时长' })">
					<img class="icon hushu" src="@/assets/images/index/live/huashu.png" mode=""></img>
					<div class="text">主话术</div>
          <div @click.stop>
            <SwitchToggle :modelValue="store.userConfig.enableMain" @change="enableMainChange" size="small"/>
          </div>
					<img class="edit" src="@/assets/images/index/live/edit.png" mode=""></img>
				</div>
				<div class="items" @click="toLiveConfig({ name: 'upvote', title: '点赞感谢' })">
					<img class="icon dianzan" src="@/assets/images/index/live/dianzan.png" mode=""></img>
					<div class="text">点赞感谢</div>
          <div @click.stop>
            <SwitchToggle :modelValue="store.userConfig.enableLike" @change="enableLikeChange" size="small"/>
          </div>
					<img class="edit" src="@/assets/images/index/live/edit.png" mode=""></img>
				</div>
				<div class="items" @click="toLiveConfig({ name: 'attention', title: '关注感谢' })">
					<img class="icon guanzhu" src="@/assets/images/index/live/guanzhu.png" mode=""></img>
					<div class="text">关注感谢</div>
          <div @click.stop>
            <SwitchToggle :modelValue="store.userConfig.enableFollow" @change="enableFollowChange" size="small"/>
          </div>
					<img class="edit" src="@/assets/images/index/live/edit.png" mode=""></img>
				</div>
				<div class="items" @click="toLiveConfig({ name: 'gift', title: '礼物感谢' })">
					<img class="icon liwu" src="@/assets/images/index/live/liwu.png" mode=""></img>
					<div class="text">礼物感谢</div>
          <div @click.stop>
            <SwitchToggle :modelValue="store.userConfig.enableGift" @change="enableGiftChange" size="small"/>
          </div>
					<img class="edit" src="@/assets/images/index/live/edit.png" mode=""></img>
				</div>
				<div class="items" @click="toLiveConfig({ name: 'greet', title: '欢迎话术' })">
					<img class="icon huanying" src="@/assets/images/index/live/huanying.png" mode=""></img>
					<div class="text">欢迎话术</div>
          <div @click.stop>
            <SwitchToggle :modelValue="store.userConfig.enableWelcome" @change="enableWelcomeChange" size="small"/>
          </div>
					<img class="edit" src="@/assets/images/index/live/edit.png" mode=""></img>
				</div>
				<div class="items" @click="toDeepseekConfig({ name: 'deepseekInterval', title: 'DeepSeek触发时长' })">
					<img class="icon deepseek" src="@/assets/images/index/live/DeepSeek.png" mode=""></img>
					<div class="text">DeepSeek</div>
          <div @click.stop="handleDeepSeekClick">
            <SwitchToggle :modelValue="store.userConfig.enableSmartReply" @change="enableSmartReplyChange" :disabled="isDeepSeekDisabled" size="small"/>
          </div>
					<img class="edit" src="@/assets/images/index/live/edit.png" mode=""></img>
				</div>
			</div>
    </div>
    <div class="correctTime baseStyle">
      <div class="title">
        <div class="text">报时设置</div>
        <!-- <switch :checked="baoshi.timekeep == 1" @change="timekeepChange"/> -->
        <SwitchToggle :modelValue="store.enableTimeData.enableTime" @change="enableTimeChange"/>
      </div>
      <div class="subTitle">报时内容</div>
      <div class="content">
        <input type="text" v-model="store.enableTimeData.timePrefix" @change="timeTextChange" placeholder="请输入前置内容"/>
        <div class="unit">{{nowTime || '0时0分'}}</div>
        <input type="text" v-model="store.enableTimeData.timeSuffix" @change="timeTextChange" placeholder="请输入后置内容"/>
      </div>
      <div class="subTitle">每隔几分钟报时</div>
      <div class="content">
        <input type="number" v-model="store.enableTimeData.timeInterval" placeholder="请输入"/>
        <div class="unit" style="text-align: left; margin-left: 12px;">分钟报时</div>
      </div>
    </div>
    <div class="live-btn-block">
      <button class="live-btn" @click="liveCloseA()">仅关闭直播</button>
      <button class="live-btn" @click="liveClose">结束并关闭云电脑</button>
    </div>
    
    <!-- <button class="live-btn" @click="liveBtnFun()">开启直播</button> -->
    <div style="height: 40px;"></div>
    
    <!-- 确认弹窗 -->
    <GlobalDialog
      v-model="showConfirmDialog"
      title="确定结束直播并关闭云电脑吗？"
      message="若确定结束直播，后台会自动关机云服务器"
      cancelText="再想想"
      confirmText="结束直播和云电脑"
      @confirm="confirmLiveClose"
      @cancel="() => console.log('用户取消了结束直播')"
    >
    </GlobalDialog>

    <GlobalDialog
      v-model="showConfirmDialogA"
      title="确定结束直播吗？"
      message="后台不会关机云服务器，请手动关机"
      cancelText="再想想"
      confirmText="结束直播"
      @confirm="confirmLiveCloseA"
      @cancel="() => console.log('用户取消了结束直播')"
    >
    </GlobalDialog>
  </div>
</template>

<style lang="scss" scoped>
.but {
  button {
    padding: 0;
  }
}
.live-btn-block {
  display: flex;
  button {
    &:first-child {
      margin-right: 5px;
    }
    &:last-child {
      margin-left: 5px;
    }


  }
}
.live-page {
  width: 100%;  
  min-height: 100vh;
  background: linear-gradient( 232deg, #E0EDFF 0%, #EAF2FB 65%, #F4FAFE 100%);
  padding: 0 16px;
  box-sizing: border-box;
  .logo-block {
    box-sizing: border-box;
    padding-top: 55px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .logo {
      width: 94px;
      height: 22px;
    }
  }
  .live {
    width: 397px;
    height: 257px;

    background: url(@/assets/images/index/live/topBg.png);
    background-size: cover;
    border-radius: 20px;
    margin-bottom: 16px;
    position: relative;
    .live-data-list-btn {
      width: 69px;
      height: 26px;
      line-height: 26px;
      background: linear-gradient( 86deg, #E8FAFE 0%, #DEE8FF 100%);
      border-radius: 15px;
      border-image: linear-gradient(180deg, rgba(255, 255, 255, 1), rgba(224, 235, 255, 1)) 2 2;
      position: absolute;
      right: 16px;
      bottom: 12px;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 12px;
      color: #006CFF;
      text-align: center;
      z-index: 99;
    }
    .live-data {
      background: url(@/assets/images/index/live/subbg.png);
      background-repeat: no-repeat;
      background-size: 100% 100%;
      width: 365px;
      height: 107px;
      position: absolute;
      left: 16px;
      top: -3px;
      padding-top: 19px;
      box-sizing: border-box;
      .posTop {
        position: absolute;
        right: 19px;
        top: 6px;
        font-family: PingFang SC, PingFang SC;
        font-weight: 600;
        font-size: 12px;
        color: #006CFF;
        text-align: center;
      }
      .item-block {
        height: 88px;
        display: flex;
        align-items: center;
        justify-content: center;
        .items {
          flex: 1;
          .text {
            font-family: PingFang SC, PingFang SC;
            font-weight: 400;
            font-size: 12px;
            color: #595959;
            text-align: center;
          }
          .number {
            font-family: PingFang SC, PingFang SC;
            font-weight: 600;
            font-size: 20px;
            color: #006CFF;
            text-align: center;
          }
        }
        .line {
          width: 1px;
          height: 19px;
          background: #DBEDFF;
        }
      }
    }
    .live-mssage {
      width: 100%;
      height: 141px;
      overflow: hidden;
      position: absolute;
      left: 0;
      top: 115px;
      padding: 0 16px;
      box-sizing: border-box;
    }
  }
  .baseStyle {
    padding: 20px 16px;
    background: #FFFFFF;
    box-sizing: border-box;
    border-radius: 10px;
    margin-bottom: 16px;
    .title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .text {
        font-family: PingFang SC, PingFang SC;
        font-weight: 600;
        font-size: 16px;
        color: #00042D;
      }
      .icon {
        width: 9px;
        height: 14px;
        background: url('@/assets/images/config/youjiantou.png');
        background-size: 100% 100%;
      }
    }
  }
  .control {
    .content {
      padding-top: 17px;
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      row-gap: 23px;
      .items {
        padding: 10px 8px 9px 10px;
        box-sizing: border-box;
        width: 111px;
        height: 93px;
        background: #F6FAFF;
        border-radius: 10px;
        position: relative;
        .icon {
          width: 30px;
          height: 30px;
        }
        .icon.deepseek {
          width: 34px;
          height: 31px;
        }
        .text {
          font-family: PingFang SC, PingFang SC;
          font-weight: 500;
          font-size: 14px;
          color: #00224F;
          line-height: 16px;
        }
        .edit {
          width: 18px;
          height: 18px;
          position: absolute;
          right: 8px;
          bottom: 9px;
        }
        
        // 为 SwitchToggle 包装器添加样式，使其靠左对齐
        & > div:has(.custom-switch) {
          position: absolute;
          left: 10px; // 靠左对齐
          bottom: 9px;
          display: flex;
          align-items: center;
          height: 18px; // 与 edit 图标高度一致
        }
      }
    }
  }
  .correctTime {
    .subTitle {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 14px;
      color: #00042D;
      padding-top: 17px;
      margin-bottom: 12px;
      border-top: 1px solid #F2F6FF;
      margin-top: 19px;
    }
    .content {
      display: flex;
      align-items: center;
      input {
        width: 140px;
        height: 40px;
        background: #FFFFFF;
        border-radius: 8px;
        border: 1px solid #DAE2EA;
        font-size: 14px;
        padding: 0 14px;
        box-sizing: border-box;
      }
      .unit {
        font-size: 14px;
        color: #999999;
        flex: 1;
        text-align: center;
        box-sizing: border-box;
      }
    }
  }
}
textarea, input {
  transition: all 0.3s ease;
}
textarea:focus-within, input:focus-within  {
  border-color: #006cff !important;
  box-shadow: 0 0 0 2px rgba(0, 108, 255, 0.1);
  background: #fff !important;
}
</style>